package com.bawan.vims.controller;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

/**
 * <p> Description	: BaseController.java </p>
 * <p> Copyright	: Copyright (c) 2015 by FITT</p>
 * <p> Author 		: ZCC </p>
 * <p> Create		: 2015年1月30日 上午10:03:35 </p> 
 * <p> version 		: 1.0 </p>
 */
public class BaseController<T> {
	protected static final Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	private Class<T> clazz;
	
	protected final void setClazz(final Class<T> clazz) {
		this.clazz = Preconditions.checkNotNull(clazz);
	}
	
	/**
	 * 打印当前使用的类方法名
	 * @return
	 */
	protected String getClassNameAndMethod(){
		StackTraceElement[] stacks = new Throwable().getStackTrace();    
        StringBuilder sb=new StringBuilder();
        sb.append("[" ).append(this.getClass().getSimpleName()).append(".").append(stacks[1].getMethodName()).append("]  ");
        return sb.toString();
	}
	
	/**
	 * 利用泛型将请求中参数转换成一个对象
	 * @param request
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	protected T getEntity(HttpServletRequest request) {
		Map<String, String[]> params = request.getParameterMap();
		
		if (params == null || params.keySet().size() == 0) {
			return null;
		}
		
		T entity = null;
		
		try {
			entity = clazz.newInstance();
			Field[] fields = clazz.getDeclaredFields();
			Method[] methods = clazz.getDeclaredMethods();
			for (Field field : fields) {
				for (Method method : methods) {
					String methodName = "set" + field.getName().substring(0,1).toUpperCase() + field.getName().substring(1);
					if (method.getName().equals(methodName) && params.get(field.getName()) != null) {
						method = clazz.getDeclaredMethod("set" + field.getName().substring(0,1).toUpperCase() + field.getName().substring(1), method.getParameterTypes());
						//获得方法的参数类型
						Class parameterType = method.getParameterTypes()[0];
						
						//设置属性值
						if (parameterType.getName().equals("java.lang.Long")) {
							method.invoke(entity, Long.parseLong(params.get(field.getName())[0].toString()));
						} else if (parameterType.getName().equals("java.lang.Integer")) {
							method.invoke(entity, Integer.parseInt(params.get(field.getName())[0].toString()));
						} else if (parameterType.getName().equals("java.lang.Float")) {
							method.invoke(entity, Float.parseFloat(params.get(field.getName())[0].toString()));
						} else if (parameterType.getName().equals("java.lang.Double")) {
							method.invoke(entity, Double.parseDouble(params.get(field.getName())[0].toString()));
						} else if (parameterType.getName().equals("java.lang.String")) {
							method.invoke(entity, String.valueOf(params.get(field.getName())[0].toString()));
						} 
					}
				}
			}
		} catch (Exception e) {
			logger.error(getClassNameAndMethod() + " occurred error:" + e.getMessage(), e);
		}
		return entity;
	}
	
	/**
	 * 获得请求request中所有的参数键值对
	 * @param request
	 * @return Map<String, String> 
	 */
	protected Map<String, String> getRequestParameter(HttpServletRequest request) {
		Map<String, String> params = new HashMap<String, String>();
		Enumeration<String> names = request.getParameterNames();
		if (names == null || !names.hasMoreElements()) {
			while(names.hasMoreElements()) {
				String name = names.nextElement();
				String value = request.getParameter(name);
				params.put(name, value);
			}
		}
		
		return params;
	}
}
